import { useState } from "react";

export default function Count() {

  const [optionValue, setOptionValue] = useState("1");
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + Number(optionValue));
  };

  const decrement = () => {
    setCount(count - Number(optionValue));
  };

  const incrementIfOdd = () => {
    if (optionValue % 2 !== 0) setCount(count + Number(optionValue));
  };

  const incrementAsync = () => {
    setTimeout(() => {
      setCount(count + Number(optionValue));
    }, 500);
  };

  return (
    <>
      <h1>当前求和为：{count}</h1>
      <select value={optionValue} onChange={(e) => setOptionValue(e.target.value)}>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>&nbsp;&nbsp;

      <button
        onClick={() => {
          increment();
        }}
      >
        +
      </button>&nbsp;&nbsp;
      <button
        onClick={() => {
          decrement();
        }}
      >
        -
      </button>&nbsp;&nbsp;
      <button
        onClick={() => {
          incrementIfOdd();
        }}
      >
        当前求和为奇数再加
      </button>&nbsp;&nbsp;
      <button
        onClick={() => {
          incrementAsync();
        }}
      >
        异步加
      </button>
    </>
  );
}
